<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<script type="text/javascript">
    require([ "dojo/_base/array", "dojo/_base/xhr", "dojo/request", "dojo/topic", "dojo/json", "dojo/_base/lang",
            "dojo/dom", "dijit/Dialog", "dojo/date" ], function(array, xhr, request, topic, JSON, lang, dom, Dialog, date) {
        var deletItemsCount = 0;
        var refreshTree = "mailfolder/refreshZtree";
        var deletItemsCount = 0;
        workplanRestForm = function(formId) {
            dijit.byId(formId).reset();
            dijit.byId("Newplancontent").setValue("");
            dijit.byId("Updateplancontent").setValue("");
            document.getElementById("IIPlanStartTime").value="";
            document.getElementById("IIPlanEndTime").value="";
            document.getElementById("IPlanStartTime").value="";
            document.getElementById("IPlanEndTime").value="";
            if (formId.indexOf('UFD') != -1) {
                var rowid = jQuery("#workplanGird").jqGrid('getGridParam', 'selrow');
                var workplan = jQuery("#workplanGird").jqGrid('getRowData', rowid);
                dijit.byId('workplanUFD').setValues(workplan);
            }
        };
        topic.subscribe("workplan/insertOrUpdate", workplanRestForm);
        var syncDB = function(url, jsonData) {
            request.post(url, {
                data : jsonData,
                headers : {
                    'Content-Type' : "application/json; charset=utf-8"
                },
                timeout : 30000
            }).then(function(response) {
                topic.publish("notifyMsgTopic", {
                    message : '操作成功!' || response,
                    type : "message",
                    duration : 1000
                });
                topic.publish(refreshTree);
                var currentPage = jQuery('#workplanGird').jqGrid('getGridParam', 'page');
                var pageSize = jQuery('#workplanGird').jqGrid('getGridParam', 'rowNum');
                var totalCount = jQuery('#workplanGird').jqGrid('getGridParam', 'records') - deletItemsCount;
                var totalPages = Math.ceil(totalCount / pageSize);
                jQuery("#workplanGird").jqGrid('setGridParam', {
                    page : currentPage > totalPages ? totalPages : currentPage
                }).trigger("reloadGrid");
            }, function(error) {
                alert(error);
            });
        };
        
        workplanSubmitForm = function(formId, type) {
            var url = "workplan/insert";
            if (type == 'u') {
                url = "workplan/update";
            }
            var form = dijit.byId(formId);
            if (form.isValid()) {
                var formData = form.getValues();
                lang.mixin(formData, {
                    userid : userid,
                    principal : username,
                    protypeid : formData['typeid']
                });
                var json = JSON.stringify(formData);
                syncDB(url, json);
                form.hide();
                topic.publish("workplan/insertOrUpdate", formId);
            } else {
                form.validate();
            }
        };
        workplanDelete = function() {
            var ids = jQuery("#workplanGird").jqGrid('getGridParam', 'selarrrow') || [];
            deletItemsCount = ids.length;
            if (ids.length > 0) {
                if (confirm('确认删除所选定的项？')) {
                    var workplan = {};
                    workplan.id = '';
                    array.forEach(ids, function(entry, i) {
                        workplan.id += entry + ",";
                    });
                    syncDB("workplan/delete", JSON.stringify(workplan));
                }
            } else {
                alert('请选择至少一条数据!');
            }
        };
        workplanQuery = function(formId) {
            var workplan = dijit.byId(formId).getValues();
            jQuery("#workplanGird").jqGrid('setGridParam', {
                postData : workplan,
                mtype : "post"
            }).trigger('reloadGrid');
        };
        workplantypeSubmitForm = function(formId, type) {
            var url = "workplantype/insert";
            if (type == 'u') {
                url = "workplantype/update";
            }
            var form = dijit.byId(formId);
            if (form.isValid()) {
                var formData = form.getValues();
                lang.mixin(formData, {
                    userid : userid
                });
                var json = JSON.stringify(formData);
                syncDB(url, json);
                form.hide();
                topic.publish("workplantype/insertOrUpdate", formId);
            } else {
                form.validate();
            }
        };
        workplantypeDelete = function() {
            var ids = jQuery("#workplantypeGird").jqGrid('getGridParam', 'selarrrow') || [];
            deletItemsCount = ids.length;
            if (ids.length > 0) {
                if (confirm('确认删除所选定的项？')) {
                    var workplantype = {};
                    workplantype.id = '';
                    array.forEach(ids, function(entry, i) {
                        workplantype.id += entry + ",";
                    });
                    syncDB("workplantype/delete", JSON.stringify(workplantype));
                }
            } else {
                alert('请选择至少一条数据!');
            }
        };
        workplantypeQuery = function(formId) {
            var workplantype = dijit.byId(formId).getValues();
            jQuery("#workplantypeGird").jqGrid('setGridParam', {
                postData : workplantype,
                mtype : "post"
            }).trigger('reloadGrid');
        };
        
        // zTree
        var addHoverDom = function(treeId, treeNode) {
            var sObj = jQuery("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || jQuery("#addBtn_" + treeNode.id).length > 0)
                return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.id
                    + "' title='新增节点' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = jQuery("#addBtn_" + treeNode.id);
            if (btn) {
                btn.bind("click", function() {
                    var zTree = jQuery.fn.zTree.getZTreeObj(treeId);
                    if (!treeNode.open) {
                        zTree.expandNode(treeNode);
                    }
                    var workplantypeIFD = dijit.byId('workplantypeIFD');
                    workplantypeIFD.setValues({
                        pid : treeNode.menuid
                    });
                    workplantypeIFD.show();
                    var handle = topic.subscribe(refreshTree, function() {
                        zTree.reAsyncChildNodes(null, "refresh");
                        handle.remove();
                    });
                    return false;
                });
            }
        };
        var removeHoverDom = function(treeId, treeNode) {
            jQuery("#addBtn_" + treeNode.id).unbind().remove();
        };
        var showRemoveBtn = function(treeId, treeNode) {
            return (treeNode.level != 0);
        };
        var showRenameBtn = function(treeId, treeNode) {
            return (treeNode.level != 0);
        };
        var beforeRename = function(treeId, treeNode, newName) {
            var zTree = jQuery.fn.zTree.getZTreeObj(treeId);
            
            if (newName.length == 0) {
                alert("节点名称不能为空.");
                setTimeout(function() {
                    zTree.editName(treeNode);
                }, 10);
                return false;
            }
            
            var workplantype = {};
            workplantype.typeid = treeNode.typeid;
            workplantype.typename = newName;
            workplantype.userid = treeNode.userid;
            
            syncDB("workplantype/update", JSON.stringify(workplantype));
            var handle = topic.subscribe(refreshTree, function() {
                zTree.reAsyncChildNodes(null, "refresh");
                handle.remove();
            });
            return true;
        };
        var beforeRemove = function(treeId, treeNode) {
            var zTree = jQuery.fn.zTree.getZTreeObj(treeId);
            zTree.selectNode(treeNode);
            var isDel = confirm("确认删除  '" + treeNode.typename + "' 吗？");
            if (isDel) {
                var workplantype = {};
                workplantype.id = treeNode.typeid;
                syncDB("workplantype/delete", JSON.stringify(workplantype));
                var handle = topic.subscribe(refreshTree, function() {
                    zTree.reAsyncChildNodes(null, "refresh");
                    handle.remove();
                });
            } else {
                return false;
            }
        };
        var beforeDrag = function(treeId, treeNodes) {
            return false;
        };
        var zTreeOnClick = function(event, treeId, treeNode) {
            var protypeid = treeNode.typeid;
            jQuery("#workplanGird").jqGrid('setGridParam', {
                postData : {
                    protypeid : protypeid,
                    userid : userid
                },
                mtype : "post"
            }).trigger('reloadGrid');
        };
        var setting = {
            async : {
                enable : true,
                url : "workplantype/queryFolderLevel"
            },
            check : {
                enable : false,
                chkboxType : {
                    "Y" : "s",
                    "N" : "p"
                }
            },
            view : {
                addHoverDom : addHoverDom,
                removeHoverDom : removeHoverDom,
                selectedMulti : false
            },
            edit : {
                enable : true,
                editNameSelectAll : true,
                showRemoveBtn : showRemoveBtn,
                showRenameBtn : showRenameBtn
            },
            data : {
                key : {
                    name : 'typename'
                },
                simpleData : {
                    enable : false,
                    idKey : 'typeid'
                }
            },
            callback : {
                beforeDrag : beforeDrag,
                beforeRename : beforeRename,
                beforeRemove : beforeRemove,
                onClick : zTreeOnClick
            }
        };
        jQuery.fn.zTree.init(jQuery("#workplanTypeTree"), setting);
    });
</script>
<div>
  <div style="width: 18%; height: 555px; float: left;" data-dojo-type="dijit/layout/AccordionContainer">
    <div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="selected:true,title:'分类管理'">
      <div>
        <ul id="workplanTypeTree" class="ztree" style="margin: 0px; padding: 0; border: 0 solid white; background: white; overflow-y: hidden;"></ul>
      </div>
    </div>
  </div>
  <div style="width: 80%; float: right;">
    <div data-dojo-type="dijit/Dialog" id="workplanIFD" title="新增">
      <div class="dijitDialogPaneContentArea">
        <table>
          <tr>
            <td><label for="typename">计划类型: </label></td>
            <td><div id="typeidSelectINS"></div>
            <input data-dojo-type="dijit/form/TextBox" name="typename" data-dojo-id="typenameIFD" style="display: none;">
            </td>
          </tr>
          <tr>
            <td><label for="planname">计划名称: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true" type="text" name="planname"></td>
          </tr>
          <tr>
            <td><label for="starttime">开始日期: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" name="starttime" style="width: 325px;" type="text" class="Wdate" id="IIPlanStartTime"
              onClick="WdatePicker({maxDate:'#F{$dp.$D(\'IIPlanEndTime\')}'})"></td>
          </tr>
          <tr>
            <td><label for="endtime">结束日期: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" name="endtime" style="width: 325px;" type="text" class="Wdate" id="IIPlanEndTime"
              onClick="WdatePicker({minDate:'#F{$dp.$D(\'IIPlanStartTime\')}'})"></td>
          </tr>
          <tr>
            <td><label for="plancontent">计划内容: </label></td>
            <td><div name="plancontent" id="Newplancontent" data-dojo-type="dijit/Editor" data-dojo-props="plugins:['bold','italic','|','cut','copy','paste','|','insertUnorderedList'], height: 100"></div>
            </td>
          </tr>
          <tr>
            <td><label for="note">备注: </label></td>
            <td><input data-dojo-type="dijit/form/SimpleTextarea" style="height: 50px;width: 480px" type="text" name="note"></td>
          </tr>
        </table>
      </div>
      <div class="dijitDialogPaneActionBar">
        <button data-dojo-type="dijit/form/Button" type="button" onclick="workplanSubmitForm('workplanIFD','i')">保存</button>
        <button data-dojo-type="dijit/form/Button" type="button" onclick="workplanRestForm('workplanIFD');">重置</button>
      </div>
    </div>
    <div data-dojo-type="dijit/Dialog" id="workplanUFD" title="更新">
      <div class="dijitDialogPaneContentArea">
        <input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, readOnly: true" type="text" name="planid" style="display: none;">
        <table>
          <tr>
            <td><label for="typename">计划类型: </label></td>
            <td><div name="typename" id="typeidSelectUPS"></div></td>
            <input data-dojo-type="dijit/form/TextBox" name="typename" data-dojo-id="typenameUFD" style="display: none;">
          </tr>
          <tr>
            <td><label for="planname">计划名称: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true" type="text" name="planname"></td>
          </tr>
          <tr>
            <td><label for="starttime">开始日期: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" name="starttime" style="width: 325px;" type="text" class="Wdate" id="IPlanStartTime"
              onClick="WdatePicker({maxDate:'#F{$dp.$D(\'IPlanEndTime\')}'})"></td>
          </tr>
          <tr>
            <td><label for="endtime">结束日期: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" name="endtime" style="width: 325px;" type="text" class="Wdate" id="IPlanEndTime"
              onClick="WdatePicker({minDate:'#F{$dp.$D(\'IPlanStartTime\')}'})"></td>
          </tr>
          <tr>
            <td><label for="plancontent">计划内容: </label></td>
            <td><div name="plancontent" id="Updateplancontent" data-dojo-type="dijit/Editor" data-dojo-props="plugins:['bold','italic','|','cut','copy','paste','|','insertUnorderedList'], height: 100"></div></td>
          </tr>
          <tr>
            <td><label for="note">备注: </label></td>
            <td><input data-dojo-type="dijit/form/SimpleTextarea" style="height: 75px;width: 322px"  type="text" name="note"></td>
          </tr>
        </table>
      </div>
      <div class="dijitDialogPaneActionBar">
        <button data-dojo-type="dijit/form/Button" type="button" onclick="workplanSubmitForm('workplanUFD','u')">保存</button>
        <button data-dojo-type="dijit/form/Button" type="button" onclick="workplanRestForm('workplanUFD');">重置</button>
      </div>
    </div>
    <div data-dojo-type="dijit/Dialog" id="workplantypeIFD" title="新增">
      <div class="dijitDialogPaneContentArea">
        <table>
          <tr>
            <td><label for="typename">类别名称: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true" type="text" name="typename"></td>

          </tr>
        </table>
      </div>
      <div class="dijitDialogPaneActionBar">
        <button data-dojo-type="dijit/form/Button" type="button" onclick="workplantypeSubmitForm('workplantypeIFD','i')">保存</button>
        <button data-dojo-type="dijit/form/Button" type="button" onclick="workplantypeRestForm('workplantypeIFD');">重置</button>
      </div>
    </div>
    <div data-dojo-type="dijit/Dialog" id="workplantypeUFD" title="更新">
      <div class="dijitDialogPaneContentArea">
        <input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, readOnly: true" type="text" name="typeid" style="display: none;">
        <table>
          <tr>
            <td><label for="typename">类别名称: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true" type="text" name="typename"></td>
          </tr>
        </table>
      </div>
      <div class="dijitDialogPaneActionBar">
        <button data-dojo-type="dijit/form/Button" type="button" onclick="workplantypeSubmitForm('workplantypeUFD','u')">保存</button>
        <button data-dojo-type="dijit/form/Button" type="button" onclick="workplantypeRestForm('workplantypeUFD');">重置</button>
      </div>
    </div>
    <fieldset>
      <legend>&nbsp;&nbsp;信息选项&nbsp;&nbsp;</legend>
      <form id="queryWorkplanForm" data-dojo-type="dijit/form/Form" method="post">
        <div style="margin-left: 5px;">
          <table>
            <tr>
              <td><label for="planname">计划名称: </label></td>
              <td><input data-dojo-type="dijit/form/TextBox" data-dojo-props="trim: true" type="text" name="planname"></td>
              <td><label for="typename">计划类型: </label></td>
              <td><input data-dojo-type="dijit/form/TextBox" data-dojo-props="trim: true" type="text" name="typename"></td>
            </tr>
          </table>
        </div>
      </form>
      <div style="padding: 5px;">
        <button id="workplanInsertBtn" data-dojo-type="dijit/form/Button" type="submit" label="新增">
        <script type="dojo/method" event="onClick" args="evt">
        require([ "dijit/form/Select","dojo/json","dojo/request", "dojo/_base/lang"], 
            function(Select,JSON,request, lang) {
              request.post("workplantype/select", {
                headers : {
                  'Content-Type' : "application/json; charset=utf-8"
                },
                timeout : 30000
              }).then(function(response) {
                var ops=JSON.parse(response);
                //ops.push({label : " ", value : " ", selected : "true"});
                if(ops && ops.length > 0) {
                  lang.mixin(ops[0], {selected : "true"})
                }
                dijit.byId("typeidSelectINS").options=[]; 
                dijit.byId("typeidSelectINS").addOption(ops);
              }, function(error) {
                alert(error);
              });
        });
        dijit.byId('workplanIFD').show();
        </script>
        </button>
        <button id="workplanDeleteBtn" data-dojo-type="dijit/form/Button" type="button" label="删除" onclick="workplanDelete();"></button>
        <button id="workplanUpdateBtn" data-dojo-type="dijit/form/Button" type="button" label="更新">
          <script type="dojo/method" event="onClick" args="evt">
          require([ "dijit/form/Select","dojo/json","dojo/request", "dojo/_base/lang" ], 
            function(Select,JSON,request,lang) {
              request.post("workplantype/select", {
                headers : {
                  'Content-Type' : "application/json; charset=utf-8"
                },
                timeout : 30000
              }).then(function(response) {
                var ops=JSON.parse(response);
                //ops.push({label : " ", value : " ", selected : "true"});
                if(ops && ops.length > 0) {
                  lang.mixin(ops[0], {selected : "true"})
                }
                dijit.byId("typeidSelectUPS").options=[]; 
                dijit.byId("typeidSelectUPS").addOption(ops);
              }, function(error) {
                alert(error);
            });
          });
            var ids = jQuery("#workplanGird").jqGrid('getGridParam', 'selarrrow') || [];
            if (ids.length != 1) {
              alert('每次只能修改一条数据!');
            } else {
              var workplan = jQuery("#workplanGird").jqGrid('getRowData', ids[0]);
              dijit.byId('workplanUFD').setValues(workplan);
              dijit.byId('workplanUFD').show();
            }
        </script>
        </button>
        <button id="workplanQueryBtn" data-dojo-type="dijit/form/Button" type="button" label="查询" onclick="workplanQuery('queryWorkplanForm');"></button>
      </div>
    </fieldset>
    <div id="gird">
      <table id="workplanGird"></table>
      <div id="workplanToolbar"></div>
    </div>
  </div>
</div>

<script type="text/javascript">

    require([ "dijit/form/Select", "dojo/json", "dojo/request" ], function(Select, JSON, request) {
        request.post("workplantype/select", {
            headers : {
                'Content-Type' : "application/json; charset=utf-8"
            },
            timeout : 30000
        }).then(function(response) {
            var ops = JSON.parse(response);
            ops.push({
                label : " ",
                value : " ",
                selected : "true"
            });
            new Select({
                name : "typeid",
                style : "width: 80%",
                options : ops,
                onChange : function(newValue) {
                    var option = this.getOptions(newValue);
                    if (option) {
                        typenameIFD.set("value", option.label || "");
                    }
                }
            }, "typeidSelectINS").startup();
            new Select({
                name : "typeid",
                style : "width: 80%",
                options : ops,
                onChange : function(newValue) {
                    var option = this.getOptions(newValue);
                    if (option) {
                        typenameUFD.set("value", option.label || "");
                    }
                }
            }, "typeidSelectUPS").startup();
            
        }, function(error) {
            alert(error);
        });
    });
</script>
<script type="text/javascript">
require([ "dojo/date" ], function(date) {
    jQuery("#workplanGird").jqGrid(
            {
                url : 'workplan/queryAsList',
                datatype : "json",
                autowidth : true,
                rownumbers : true,
                height : 'auto',
                colNames : [ '计划ID', '计划名称', '计划内容', '开始日期', '结束日期', '类型名称', '创建人', '计划类别ID', '发布范围', '参与人', '负责人',
                        '备注', '状态', '是否为个人计划', '图标', '附件ID', '是否生效' ],
                colModel : [ {
                    name : 'planid',
                    index : 'planid',
                    width : 60,
                    key: true,
                    hidden : true,
                    align : 'center'
                }, {
                    name : 'planname',
                    index : 'planname',
                    width : 150,
                    align : 'center'
                }, {
                    name : 'plancontent',
                    index : 'plancontent',
                    hidden : true
                }, {
                    name : 'starttime',
                    index : 'starttime',
                    align : 'center',
                    width : 140
                }, {
                    name : 'endtime',
                    index : 'endtime',
                    align : 'center',
                    width : 140
                }, {
                    name : 'typename',
                    index : 'typename',
                    align : 'center',
                    width : 80
                }, {
                    name : 'userid',
                    index : 'userid',
                    hidden : true
                }, {
                    name : 'protypeid',
                    index : 'protypeid',
                    width : 60,
                    hidden : true
                }, {
                    name : 'issuescope',
                    index : 'issuescope',
                    hidden : true
                }, {
                    name : 'participants',
                    index : 'participants',
                    hidden : true
                }, {
                    name : 'principal',
                    index : 'principal',
                    hidden : true
                }, {
                    name : 'note',
                    index : 'note',
                    hidden : true
                }, {
                    name : 'status',
                    index : 'status',
                    hidden : true
                }, {
                    name : 'ispersonal',
                    index : 'ispersonal',
                    hidden : true
                }, {
                    name : 'icon',
                    index : 'icon',
                    hidden : true
                }, {
                    name : 'fileid',
                    index : 'fileid',
                    hidden : true
                }, {
                    name : 'judge',
                    index : 'judge',
                    align : 'center',
                    width : 80
                } ],
                rowNum : 15,
                rowList : [ 15, 20, 25, 30 ],
                pager : '#workplanToolbar',
                recordpos : 'right',
                viewrecords : true,
                sortorder : "desc",
                jsonReader : {
                    repeatitems : false
                },
                gridComplete : function() {
                    var ids = jQuery("#workplanGird").jqGrid('getDataIDs');
                    for ( var i = 0; i < ids.length; i++) {
                        var cl = ids[i];
                        var workplan = jQuery("#workplanGird").jqGrid('getRowData', cl);
                        var dateFormat = new DateFormat("yyyy-MM-dd HH:mm:ss");
                        var starttime = dateFormat.parse(workplan.starttime);
                        var endtime = dateFormat.parse(workplan.endtime);
                        var mydate = new Date();
                        var ju1 = date.compare(mydate, starttime, "datetime");
                        var ju2 = date.compare(mydate, endtime, "datetime");
                        var ans ="";
                        if (ju1 < 0 ){
                            ans = "未生效";
                        }else if (ju2 < 0 ){
                            ans = "已生效";
                        }else {
                            ans = "已失效";
                        };
                        jQuery("#workplanGird").jqGrid('setRowData', cl, {
                            judge : ans
                        });
                    }
                },
                multiselect : true,
                shrinkToFit : false,
                caption : "工作计划列表"
            });
    jQuery("#workplanGird").jqGrid('navGrid', '#workplanToolbar', {
        edit : false,
        add : false,
        del : false,
        search : false,
        refresh : true
    });    
});
</script>
